package es.denisneuf.course
{
	import flash.events.EventDispatcher;
	import flash.events.Event;
	
	import mx.utils.ObjectUtil;
	//import flash.utils.describeType;
	
	//import flash.utils.getDefinitionByName;
	//import flash.utils.getQualifiedClassName;
	//import flash.utils.getQualifiedSuperclassName;
	//import mx.rpc.*;
	//import mx.rpc.xml.SimpleXMLEncoder;
	
	import mx.rpc.xml.SimpleXMLDecoder;
	import mx.collections.ArrayCollection;
	//import mx.collections.XMLListCollection;
	import mx.collections.*;
	
	import flash.xml.XMLDocument;

	//import flash.events.Event;
    //import flash.net.SharedObject;
    //import flash.net.SharedObjectFlushStatus;
    //import flash.events.NetStatusEvent;
	import es.denisneuf.core.managers.*;
    
    //Debug
    
    //import com.luminicbox.log.*;
    //import com.luminicbox.log.Logger;
    
    //import flash.external.*;
	
	public class Course extends EventDispatcher
	{

		public static var className:String = "Course";
		public static var packageName:String = "es.denisneuf.course";
		public static var version:String = "1.0.01";
		public static var author:String = "Daniel Alvaro";

		private static var instance:Course = null;
		
		private var _xml:XML;
		
		public var myCursor:IViewCursor;
		
		private var _suspend:SuspendDataManager;
		private var sdata:String;
		
		private var _score:ScoreManager;
		private var _interactions:InteractionsManager;
		private var _objectives:ObjectivesManager;
		
		private var _courseTotalPages:int;
		
		private var resultObj:Object;
		
		//private static var log:Logger = new Logger( "sample#1" );
		
		public static var ONCHANGEITEM:String = "onChangeItem";
		private static var KTIME:Date = new Date();
		private static var KMS:Number;		
		
		//private var moduleXML:XMLList;
		
	    public static function getInstance():Course {
	         if (instance == null) {
	            instance = new Course ();
	          }
	         return instance;
	    }		
		
		public function Course():void
		{
		}
		
		public function ParseItems(itemsInput:XML):void {

		
		
		//log.addPublisher( new ConsolePublisher() );
		
		var suspendData:String="X209MTAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAmX289YjJJd0kxVjBhV3hwZW1GeUlHeGhjeUJrYVhOMGFXNTBZWE1nWTJGeWNHVjBZWE1nWkdVZ1kyOXljbVZ2TGlOdUkzeHZZakVqUlhOamNtbGlhWElnZVNCbGJuWnBZWElnWTI5eWNtVnZjeUJsYkdWamRITHpibWxqYjNNdUkyNGpmRzlpTWlOQlpHcDFiblJoY2lCMGIyUnZJSFJwY0c4Z1pHVWdZWEpqYUdsMmIzTWdZU0IxYmlCdFpXNXpZV3BsTGlOdUkzeHZZak1qVW1WamFXSnBjaUI1SUd4bFpYSWdiV1Z1YzJGcVpYTXVJMjRqZkc5aU5DTlNaWE53YjI1a1pYSWdlU0J5WldWdWRtbGhjaUJ0Wlc1ellXcGxjeTRqYmlOOGIySTFJMFpwYm1Gc2FYcGhjaUJ0ODJSMWJHOHVJMjRq";
		
		sdata = suspendData; //Fix suspend data to check class manager
		
		
		var initialPage:String = "[0],0";
		
		
		
		var myList:XMLList = itemsInput['ITEM'];
		
		var order:int = 0;

		for (var i:int = 0; i < myList.length(); i++) {

			itemsInput['ITEM'][i].@['__LINEAL_ID__'] = order;
			
			order = order + 1;
			
			if (itemsInput['ITEM'][i].hasOwnProperty('ITEM')){
				
				var mySubList:XMLList = itemsInput['ITEM'][i].ITEM;
				
				for (var j:int = 0; j < mySubList.length(); j++) {
					
					mySubList[j]..@['__LINEAL_ID__'] = order;
					
					order = order + 1;
					
				}
				
					

			}
			
			
		
		}
		
		//trace (itemsInput.toXMLString());
		
		//log.debug('itemsInput');
		//log.debug(itemsInput);
		
		var xmlStr:String = itemsInput.toString();
        var xmlDoc:XMLDocument = new XMLDocument(xmlStr);
        var decoder:SimpleXMLDecoder = new SimpleXMLDecoder(true);
        resultObj = decoder.decodeXML(xmlDoc);
        
        //log.debug('resultObj');
        //log.debug(resultObj);
				
		trace (ObjectUtil.toString(resultObj));
		
		//trace ( describeType(resultObj) );
		
		//trace ( getQualifiedClassName (resultObj) );
		
		//trace ( getQualifiedSuperclassName (resultObj) );
		
		
		/*
		for(var s:String in resultObj) {
                trace("prop :: "+s);
                trace("value :: "+resultObj[s]);
        } 
        */
		
		//trace ('-->' + resultObj.MODULO.ITEM + "___" + getQualifiedClassName(resultObj.MODULO.ITEM));
		//*************
		//var itemCollection:ArrayCollection = resultObj.MODULO.ITEM; //WARNING DYNAMIC PROPERTY
		//**************
		//log.debug('itemCollection');
		//log.debug(itemCollection);
		
		//log.debug('itemCollection.source');
		//log.debug(itemCollection.source);
		//trace (itemCollection.source);
		
		//myCursor=itemCollection.createCursor();
		
		//beforeFirst movePrevious()
		/*
		while (! myCursor.afterLast) {
        	myCursor.moveNext();
		}
		*/
		//trace ('Items to Last: ' + countLast(myCursor));
		//trace ('Items to First: ' + countFirst(myCursor));
		//trace (myCursor.current);
		
		
        //var ClassReference:Class = getDefinitionByName("mx.utils.ObjectProxy") as Class;
        //var instance:Object = new ClassReference();
		
		//trace (instance);
		
		}
	
        public function countLast(theCursor:IViewCursor):int {
            var counter:int=0;
            // Set a bookmark at the current cursor location.
            var mark:CursorBookmark=theCursor.bookmark;
            // Move the cursor to the end of the Array.
            // The moveNext() method returns false when the cursor
            // is after the last item.
            while (theCursor.moveNext()) {
                counter++;
            }
            // Return the cursor to the initial location.
            theCursor.seek(mark);
            return counter;
        }
        
         public function countFirst(theCursor:IViewCursor):int {
            var counter:int=0;
            // Set a bookmark at the current cursor location.
            var mark:CursorBookmark=theCursor.bookmark;
            // Move the cursor to the end of the Array.
            // The moveNext() method returns false when the cursor
            // is after the last item.
            while (theCursor.movePrevious()) {
                counter++;
            }
            // Return the cursor to the initial location.
            theCursor.seek(mark);
            return counter;
        }       	
	
		
		public function set xml (newXML:XML):void{
			
			_xml = newXML;
			///////////////////			
			ParseItems (_xml);
			///////////////////
			
			_suspend = new SuspendDataManager( sdata );
			
			_score = new ScoreManager( );
			
			_interactions = new InteractionsManager( );
			
			_objectives = new ObjectivesManager( ) ;
			
			//trace ("sdm.getData( _m="+ _suspend.getData('_m') +" )");

		}
		
		public function get xml ():XML{
			return _xml;
		}
		
		
		public function init ():void{
			
		KMS = KTIME.getTime();	
		//**************		
		var itemCollection:ArrayCollection = resultObj.MODULO.ITEM; //WARNING DYNAMIC PROPERTY
		//**************
		//log.debug('init itemCollection');
		//log.debug(itemCollection);
		
		//log.debug('itemCollection.source');
		//log.debug(itemCollection.source);
		//trace (itemCollection.source);
		
		myCursor=itemCollection.createCursor();
		//trace ('cursor');
		//trace (myCursor.current);
		//log.debug(myCursor.current);
		
		//TO START KONSTANTS
		_courseTotalPages = getTotalPages ();
		
		
		
		
		}
		
		
		public function initCourse():void{
		
			dispatchEvent( new Event(Course.ONCHANGEITEM) );
		
		}	
		
		public function get courseTotalPages ():int{
		
			return _courseTotalPages;
		
		}
		
		
		public function getTotalPages():int
		
		{
			
			var itemCollection:ArrayCollection = resultObj.MODULO.ITEM; //WARNING DYNAMIC PROPERTY

			var max:int = itemCollection.length;
			
			var debug:String = '';
			
			var totalpages:int = 0;
			
			for (var i:int = 0; i < max; i++){
				
				
				
				debug += '__LINEAL_ID__ ' + itemCollection[i].__LINEAL_ID__ ;
				
				debug += ' paginas ' + itemCollection[i].paginas ;
				
				debug += ' titulo ' + itemCollection[i].titulo ;
				
			
				totalpages += int(itemCollection[i].paginas);
				
				//trace (itemCollection[i].ITEM);
				
				if (itemCollection[i].ITEM){
				
				//trace (itemCollection[i].ITEM.list);
				//trace (itemCollection[i].ITEM.length);
				
				var maxsub:int = itemCollection[i].ITEM.length;
				
				for (var j:int = 0; j < maxsub; j++){
					
					//trace (itemCollection[i].ITEM[j]);
					debug += '__LINEAL_ID__ ' + itemCollection[i].ITEM[j].__LINEAL_ID__ ;
					
					debug += ' paginas ' + itemCollection[i].ITEM[j].paginas ;
					
					debug += ' titulo ' + itemCollection[i].ITEM[j].titulo ;					
					
					totalpages += int(itemCollection[i].ITEM[j].paginas);
					
				}	
				
				
				
				}
				
				//itemCollection[i].__LINEAL_ID__;
			
			}
			
			//trace ( totalpages );
			
			//trace ('getTotalPages() ' + totalpages + ' typeof ' + typeof(totalpages) );
			
			return totalpages;
		
		}
		

			
		
		/*
		public function setIDS(_elements:XMLList):void{
			
			var max:int = _elements.length();
	
			for (var i:Number = 0; i<max; i++) {
				_elements[i].@['__LINEAL_ID__'] = i;
			}
			
			trace (_elements);			
		
		}  
		*/
		
		
					
	}
}